#include "PacketWriter.h"

PacketWriter::PacketWriter(string* device, int inject_type)
{
	this -> err = new char[LIBNET_ERRBUF_SIZE];
	this -> device = new char[device->length()+1];//+1 for null char?
	strcpy(this->device,device->c_str());
	this -> lnet = libnet_init(inject_type,
					this->device,
					this->err);
	if (this->lnet == NULL)
	{
		cout << "Error initializing libnet: " <<  strerror(errno) << endl;
		cout << err << endl;
		exit(1);
	}
	this -> hwaddr = libnet_get_hwaddr(this->lnet);
	if (this->hwaddr == NULL)
	{
		cout << "Error getting hardware address: " << libnet_geterror(this->lnet) << endl;
		exit(1);
	}
}

PacketWriter::~PacketWriter()
{
	libnet_destroy(this->lnet);
	delete this -> err;
	free(this->device);
}

void PacketWriter::write()
{
	if (libnet_write(this->lnet) == -1)
	{
		cout << "Error writing packet: " << libnet_geterror(this->lnet) << endl;
		exit(1);
	}
}
